import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import routes from './publicRoutes'
import store from '../store'
import {
  getToken
} from '@/utils/getToken'

Vue.use(Router)
// const originalPush = Router.prototype.push
// Router.prototype.push = function push (location) {
//   return originalPush.call(this, location).catch(err => err)
// }

const router = new Router({
  scrollBehavior: () => ({
    y: 0
  }),
  routes
})

const isHavePerm = (key) => {
  return store.state.user.userPermissions.indexOf(key) > -1
}

const createRouter = (menu) => {
  let routes = [{
    path: '/',
    redirect: '/index',
    name: 'MainPage',
    component: () => import('@/Layout/Layout.vue'),
    children: []
  }]
  menu.map(item => {
    let children = []
    if (isHavePerm(item.name)) {
      if (item.children) {
        item.children.map(items => {
          if (isHavePerm(items.name)) {
            children.push({
              path: items.path,
              name: items.name,
              component: resolve => require([`@/pages/${items.component}`], resolve),
              // component: () => import(`@/pages/${items.component}`),
              hidden: isHavePerm(items.name) && items.hidden,
              meta: {
                ...items.meta
              }
            })
          }
        })
        routes.push({
          path: item.path,
          name: item.name,
          component: () => import('@/Layout/Layout.vue'),
          hidden: isHavePerm(item.name) && item.hidden,
          children: children,
          meta: {
            ...item.meta
          }
        })
      } else {
        routes[0].children.push({
          path: item.path,
          name: item.name,
          component: resolve => require([`@/pages/${item.component}`], resolve),
          hidden: isHavePerm(item.name) && item.hidden,
          meta: {
            ...item.meta
          }
        })
      }
    }
  })
  return routes
}

const asyncRoutes = createRouter(store.state.user.permissions)
// const asyncRoutes = createRouter(store.state.user.loginUserPermission)
router.addRoutes(asyncRoutes)

// 白名单,不需要登录的路由
let whiteList = ['/login', '/404']
const IS_PROD = process.env.NODE_ENV === 'production'
if (IS_PROD) {
  whiteList = ['/login', '/404']
} else {
  whiteList = ['/login', '/404', '/test']
}

router.beforeEach((to, from, next) => {
  // 显示加载进度条
  NProgress.start()

  // document.title 更改
  const VueAppHtmlTitle = process.env.VUE_APP_HTML_TITLE ? process.env.VUE_APP_HTML_TITLE + ' - ' : ''
  const VueAppEnv = process.env.VUE_APP_ENV ? process.env.VUE_APP_ENV + ' - ' : ''
  if (to.meta.title) {
    document.title = VueAppEnv + VueAppHtmlTitle + to.meta.title || ''
  } else {
    document.title = VueAppEnv + VueAppHtmlTitle
  }

  // 页面不存在路由表中 =》 404
  if (to.matched.length === 0) {
    next('/404')
    NProgress.done()
  } else {
    const Token = getToken()
    if (Token) {
      // 登录
      if (to.path === '/login') {
        next({
          path: '/'
        })
        NProgress.done()
      } else {
        next()
      }
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 跳转之后
router.afterEach((to) => {
  NProgress.done()
})

export default router
